package server;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;


import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;

import data.Data;

public class GetTrackIp extends Thread{
	DBObject domain;
	public GetTrackIp(DBObject domain)
	{
		this.domain=domain;
		this.start();
	}
	public void run()
	{
		String content = "";
		try {

			URL dataURL = new URL("http://whatismyipaddress.com/ip/"+domain.get("name"));
			
			BufferedReader reader = new BufferedReader(new InputStreamReader(dataURL.openStream(), Charset.forName("utf-8")));
			
			while(1==1)
			{
				String str = reader.readLine();
				if(str==null) break;
				content+=str;
				
			}
			
			Document doc = Jsoup.parse(content);

			BasicDBObject info = new BasicDBObject();
			
			DBCollection coll = Data.data("domain");
			
			try {
				info.put("jsp",doc.select("div[id=section_content]").select("table").get(0).select("td").get(1).text());
			} catch (Exception e) {
				// TODO: handle exception
			}
			try {
				info.put("organization",doc.select("div[id=section_content]").select("table").get(0).select("td").get(2).text());
			} catch (Exception e) {
				// TODO: handle exception
			}
			try {
				info.put("proxy",doc.select("div[id=section_content]").select("table").get(0).select("td").get(3).text());
			} catch (Exception e) {
				// TODO: handle exception
			}
			try {
				info.put("type",doc.select("div[id=section_content]").select("table").get(0).select("td").get(4).text());
			} catch (Exception e) {
				// TODO: handle exception
			}
			try {
				info.put("assignment",doc.select("div[id=section_content]").select("table").get(0).select("td").get(5).text());
			} catch (Exception e) {
				// TODO: handle exception
			}
			try {
				info.put("country",doc.select("div[id=section_content]").select("table").get(1).select("td").get(0).text());
			} catch (Exception e) {
				// TODO: handle exception
			}
			try {
				info.put("state",doc.select("div[id=section_content]").select("table").get(1).select("td").get(1).text());
			} catch (Exception e) {
				// TODO: handle exception
			}
			try {
				info.put("city",doc.select("div[id=section_content]").select("table").get(1).select("td").get(2).text());
			} catch (Exception e) {
				// TODO: handle exception
			}
			
			BasicDBObject up = new BasicDBObject();
			
			up.put("trackip", info);
			
			BasicDBObject set = new BasicDBObject("$set", up);
			coll.update(domain, set);
		} catch (Exception e) {
			
			e.printStackTrace();
		}

	}
//	public static void main( String args[])
//	{
//		new GetTrackIp("50.17.209.163");
//	}
}
